package cn.hdu.liang.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

class SimplePriorities2 implements Runnable {
    private int countDown = 5;

    @Override
    public String toString() {
        return Thread.currentThread() + " : " + countDown;
    }

    @Override
    public void run() {
        while(true) {
            for(int i = 1; i < 1000; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
                if(i % 100 == 0) {
                    Thread.yield();
                }
            }
            System.out.println(this);
            if(--countDown == 0) {
                return;
            }
        }
    }
}

class PriorityThreadFactory implements ThreadFactory {
    private final int priority;

    public PriorityThreadFactory(int priority) {
        this.priority = priority;
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setPriority(priority);
        return t;
    }
}


public class Exam9 {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new PriorityThreadFactory(Thread.MIN_PRIORITY));
        for(int i = 0; i < 5; i++) {
            exec.execute(new SimplePriorities2());
        }
        Thread.yield();
        exec.shutdown();
        exec = Executors.newCachedThreadPool(new PriorityThreadFactory(Thread.MAX_PRIORITY));
        exec.execute(new SimplePriorities2());
        Thread.yield();
        exec.shutdown();
    }
}
